const gjjGetTokenUrl    = "https://t.51gjj.com/gjj/getToken";
const gjjH5QueryPageUrl = "https://t.51gjj.com/gjj";
const gjjDataUrl        = "http://b.jianbing.com/gjj_v3/gjj/fetch_manual";
const getGjjDataUrl        = "https://t.51gjj.com/gjj/getGjjData";
const cid = 0;
//php通知接口地址
const notifyUrl     = 'http://b.jianbing.com/ds/gjj/relay/partnersNotify';
const notifyUrl_dev = 'http://kaifa.jianbing.com/ds/gjj/relay/partnersNotify';

// var baseServer = require('./serverBase3').config(cid);
// var BS         = baseServer;

var baseServer = require('../../lib/myCommon');

var BS = new Object();
(async function cfgLoading(){
    BS = await baseServer.config(cid);
})();


var http     = require('http');
var https    = require('https');
var request  = require('request');
var fs       = require('fs');
var myDB     = require('../../lib/myDB');
var url      = require('url');
var config   = require('config');
var schedule = require('node-schedule');

//回调修复
var reCallback = async function(req,res){
        //myNum 最大回调记录；
        let myNum    = BS.getParams(req,'myNum',0);
        try{

            let limitNum = 60;
            let addNum = 30;
            if(myNum<addNum){
                addNum = myNum;
            };

            let resource = await myDB.getDB('nodeGjjDB').getRowAsync('select count(1) maxItem from sys_surname where partnerCid=?',[45]);
            let maxItem = resource.maxItem;

            let logic = async function (limitNum,addNum){
                console.error('in');
                let surnameList = await myDB.getDB('nodeGjjDB').queryAsync('select sid from sys_surname where addTime>? and partnerCid=? limit ?,?',['2018-03-24',45,limitNum,addNum]);
                if(!surnameList){
                    console.error('【cron/reCallback】surnameList='+JSON.stringify(surnameList));
                    throw "surnameList empty";
                }else{
                    console.log('【cron/reCallback】surnameList='+JSON.stringify(surnameList));
                }

                for(let i=0; i<surnameList.length; i++){
                    let surSid = surnameList[i].sid;
                    if(!surSid){throw "surname error";}

                    let surnameArr = await myDB.getDB('nodeGjjDB').getRowAsync('select sid,userSid,orderSn from sys_surname where partnerCid=? and sid=?',[45,surSid]);
                    console.log('【cron/reCallback】surnameArr='+JSON.stringify(surnameArr));
                    let userSid    = BS.getValue(surnameArr,'userSid',0);
                    let surnameSid = BS.getValue(surnameArr,'sid',0);
                    let orderSn    = BS.getValue(surnameArr,'orderSn','');
                    if(!userSid){console.error('【cron/reCallback】userSid=0'); throw "userSid=0";}
                    if(!userSid){console.error('【cron/reCallback】surnameSid=0'); throw "surnameSid=0";}
                    if(!userSid){console.error('【cron/reCallback】orderSn empty'); throw "orderSn empty";}

                    let userArr = await myDB.getDB('nodeGjjDB').getRowAsync('select passport from sys_wld_user where sid=?',[userSid]);
                    let passport = BS.getValue(userArr,'passport',0);
                    if(!passport){console.error('【cron/reCallback】passport=0'); throw "passport=0";}

                    let orderArr = await myDB.getDB('nodeGjjDB').getRowAsync('select sid from sys_order_list where orderSn=?',[orderSn]);
                    let orderSid = BS.getValue(orderArr,'sid',0);
                    if(!orderSid){console.error('【cron/reCallback】orderSid=0'); throw "orderSid=0";}

                    //后端回调地址

                    let callbackUrl = "https://rest.wolaidai.com/wedefend-gateway/api/partner/gjj51_callback";
                    // let devCallbackUrl = "http://kaifa.jianbing.com/ds/help_page/callback_confirm";

                    let sendData = {
                        code:0,
                        data:{
                            u:passport,
                            job_sid:orderSid,
                            surname_sid:surnameSid,
                            result:'success',
                            state:2,
                            yys_cid:45
                        },
                        notifyUrl:callbackUrl
                    };

                    if(callbackUrl){
                        sendData.notifyUrl = sendData.notifyUrl+'?d='+encodeURIComponent(JSON.stringify(sendData.data));
                    }

                    //后端通知合作方
                    let result = await BS.notify(notifyUrl_dev,sendData);
                    console.log('【cron/reCallback】proUrl='+notifyUrl_dev+' sendData='+JSON.stringify(sendData)+' result'+JSON.stringify(result));
                    if(result.data.status_code && result.data.status_code!=200){
                        console.error('【cron/reCallback】error1');
                    }
                    //通知开发
                    // let devResult = await BS.notify(devCallbackUrl,sendData);
                    // console.log('【cron/reCallback】devUrl=http://kaifa.jianbing.com/ds/help_page/callback_confirm sendData='+JSON.stringify(sendData)+' result='+JSON.stringify(devResult));
                    // if(devResult.data.status_code && devResult.data.status_code!=200){
                    //     console.error('【cron/reCallback】error2');
                    // }
                }

                return "";
            }

            let myTime = setInterval(function(){
                console.log('【cron/reCallback】setInterval 正在从'+limitNum+' ~ '+(limitNum+addNum));
                let wuyong = logic(limitNum,addNum);
                limitNum += addNum;

                console.log('limitNum='+limitNum+' maxItem='+maxItem+' limitNum='+limitNum+' myNum='+myNum);
                if(limitNum > maxItem || limitNum >= myNum){
                    console.log('【cron/reCallback】setInterval 结束');
                    clearInterval(myTime);
                }
            },30000);

            res.send({'code':0,'msg':' start ok'});
        }catch(err){
            res.send({code:"-1",msg:err});
        }

    }

/**
 * log表 清理
 * @param days 几天前的数据清理
 * @returns {Promise.<void>}
 */
var sys_open_h5_log = async function(days){
    days = days || 7;
    var time1 = new Date().getTime()-1000*60*60*24*days;
    var deadline = new Date(time1).toLocaleString();
    var openGjjCount = await myDB.getDB('nodeGjjDB').getRowAsync('select count(1) count from sys_open_h5_log where time<?',[deadline]);

    console.log('[zzbCron/sys_open_h5_log] deadline='+deadline);
    console.log('[zzbCron/sys_open_h5_log] openGjjCount='+JSON.stringify(openGjjCount));

    await myDB.getDB('nodeGjjDB').queryAsync('delete from sys_open_h5_log where time<?',[deadline]);

}

/**
 * order表 转存&&清理
 * @param days 几天前的数据转存
 * @returns {Promise.<void>}
 */
var sys_order_list = async function(days,limitNum){
    try{
        days = days || 7;
        limitNum = limitNum || 1;
        var time1 = new Date().getTime()-1000*60*60*24*days;
        var deadline = new Date(time1).toLocaleString();
        console.log('[zzbCron/sys_order_list] deadline='+deadline);

        var orderSid     = 0;
        var orderInfo    = new Array();
        var orderCount   = 0;

        var logic = async function (){
            // userSid,partnerCid,orderSn,taskStatus,taskMsg,cityId,createTime,callbackTime
            var orderArr = await myDB.getDB('nodeGjjDB').getRowAsync('select count(1) count from sys_order_list where callbackTime<?',[deadline]);
            if(!orderArr.count){
                // throw "[zzbCron/sys_order_list] get count error 没有订单";
                console.error("[zzbCron/sys_order_list] get count error 没有订单");
                return false;
            }

            var orderCount = orderArr.count;
            console.log('[zzbCron/sys_order_list] orderCount='+orderCount);

            var orderInfoArr = await myDB.getDB('nodeGjjDB').queryAsync('select * from sys_order_list where callbackTime<? limit ?',[deadline,limitNum]);
            if(orderInfoArr){
                for(var i=0; i<orderInfoArr.length; i++){
                    orderInfo = orderInfoArr[i];
                    orderSid  = orderInfo.sid;
                    if(!orderSid){
                        continue;
                    }

                    //写入
                    console.log('[zzbCron/sys_order_list] sys_order_list_bak 写入 orderInfo='+JSON.stringify(orderInfo));

                    var resOrder = await myDB.getDB('nodeGjjDB').queryAsync('insert into sys_order_list_bak (sid,userSid,partnerCid,orderSn,taskStatus,taskMsg,cityId,createTime,callbackTime) value (?,?,?,?,?,?,?,?,?)',
                        [orderInfo.sid,orderInfo.userSid,orderInfo.partnerCid,orderInfo.orderSn,orderInfo.taskStatus,orderInfo.taskMsg,orderInfo.cityId,orderInfo.createTime,orderInfo.callbackTime]);
                    //写入出错
                    if(!resOrder || !resOrder.insertId){
                        console.error('[zzbCron/sys_order_list] sys_order_list_bak 写入失败 sqlRet='+JSON.stringify(ret)+' orderInfo='+JSON.stringify(orderInfo));
                        continue;
                    }
                    //清理
                    await myDB.getDB('nodeGjjDB').queryAsync('delete from sys_order_list where sid=? and callbackTime<?', [orderSid,deadline]);
                }
            }

            //还有订单继续
            if(orderCount-limitNum > 0){
                setTimeout(function(){
                    var r = logic();
                },1000);
            }
        }

        var r = logic();

    }catch(err){
        console.error('[zzbCron/sys_order_list] err '+JSON.stringify(err));
    }
}

var myAxios = require('../../lib/myAxios');
var url = "http://tv.51gjj.com:8080/ServiceTest/getLoginParamInfo";
var sys_surname = async function(req,res){
    var orderSnList = await myDB.getDB('nodeGjjDB').queryAsync('select orderSn from sys_surname where cityId=?',[0]);
    for(let i=0; i<orderSnList.length; i++){
        var orderSn = orderSnList[i].orderSn;
        if(orderSn){
            var option = {"type":"gjj", "orderId":orderSn}
            console.log('orderSn='+orderSn);
            var result = await myAxios.post(url,option,{headers: {'Content-Type': 'application/json'}});
            if(result.data.Cid){
                console.log('修复成功');
                await myDB.getDB('nodeGjjDB').queryAsync('update sys_surname set cityId=? where orderSn=?',[result.data.Cid,orderSn]);
            }else{
                console.error('cityID empty '+JSON.stringify(result.data));
            }
        }else{
            console.error('orderSn empty '+JSON.stringify(orderSn));
        }
    }
    res.send('ok');
}

var test = function (req,res){
    console.log('[zzbCron/test] in '+JSON.stringify(req.body));
    var r = sys_order_list(7,10);
    res.send({state:'ok'});

}

// module.exports = MyCron;
exports.reCallback = reCallback;
exports.test       = sys_surname;

//定时脚本
//每5天清理一次数据表
var job = schedule.scheduleJob('30 4 * * *', function(){
    //var r = sys_open_h5_log(7);
    var r = sys_order_list(7,10);
});

